<?php
namespace api\modules\h5\controllers\cart;

use backend\widgets\provinces\Provinces;
use common\models\cart\Cart;
use common\models\goods\Goods;
use yii\data\ActiveDataProvider;
use Yii;
use yii\web\NotFoundHttpException;
use api\controllers\OnAuthController;
use common\enums\StatusEnum;
use common\helpers\ResultDataHelper;
use common\models\store\Store;

/**
 * 购物车接口
 *
 * Class InfoController
 * @package api\modules\h5\controllers\cart
 * @property \yii\db\ActiveRecord $modelClass
 * @author tjj
 */
class InfoController extends OnAuthController
{
    public $modelClass = 'common\models\cart\Cart';

    /**
     * 列表
     * @return ActiveDataProvider
     */
    public function actionIndex()
    {
        $query = $this->modelClass::find()
            ->where(['buyer_id'=>Yii::$app->user->identity->member_id])
            ->andWhere(['>','goods_num',0])
            ->select([])
            ->with(['goods'])
            ->asArray();

        return new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => Yii::$app->params['user.pageSize'],
                'validatePage' => false,// 超出分页不返回data
            ],
        ]);
    }

    /**
     * @return array|mixed|\yii\db\ActiveRecord[]
     */
    public function actionDeleteBatch()
    {
        $request = Yii::$app->request;
        $ids = $request->post('ids')??[];

        $ids = is_array($ids)?$ids:json_decode($ids,true);

        if(!empty($ids)){
            $cart_list = Cart::find()
                ->where(['buyer_id'=>Yii::$app->user->identity->member_id])
                ->andWhere(['in','cart_id',$ids])
                ->select(['cart_id'])
                ->asArray()
                ->all();

            $final_cart_ids =  array_column($cart_list,'cart_id');

            $update_num = Cart::updateAll(['goods_num'=>0],['in','cart_id',$final_cart_ids]);

            return $update_num;
        }else
            return ResultDataHelper::api(422, '栏目不能为空');
    }

    /**
     * 刺入购物车
     * @return mixed|\yii\db\ActiveRecord
     * @throws NotFoundHttpException
     */
    public function actionCreate()
    {
        $request = Yii::$app->request;
        $store_id = $request->post('store_id')??0;
        $goods_ids = $request->post('goods_ids')??[];

        if(!$store_id){
            throw new NotFoundHttpException('店铺参数有误.');
        }
        $this->checkMemberStore($store_id);
        $store = Store::findOne($store_id);

        $goods_ids = is_array($goods_ids)?$goods_ids:json_decode($goods_ids,true);

        if(!empty($goods_ids)){
            //我的购物车列表
            $cart_list = Cart::find()
                ->where(['buyer_id'=>Yii::$app->user->identity->member_id])
                ->indexBy('goods_id')
                ->asArray()
                ->all();

            $ids = array_column($goods_ids, 'goods_id');
            $goods_list = Goods::find()
                ->where(['in','goods_id',$ids])
                ->andWhere(['status'=>StatusEnum::ENABLED])
                ->select(['goods_id','goods_name','goods_price','goods_image','goods_storage'])
                ->indexBy('goods_id')
                ->asArray()
                ->all();

            $CartModel = new Cart();
            foreach ($goods_ids as $goods_item){
                $goods = $goods_list[$goods_item['goods_id']]??null;
                if($goods){
                    if(isset($cart_list[$goods['goods_id']])){
                        //已经存在购物车的商品，只需要数量++
                        $cart_id = $cart_list[$goods['goods_id']];
                        $cart_model = Cart::findOne($cart_id);
                        if($cart_model){
                            $cart_model->goods_num += $goods_item['num'];
                            $cart_model->save();
                        }
                    }else{
                        $cart_model = clone  $CartModel;
                        $cart_model->attributes = [
                            'buyer_id'=>Yii::$app->user->identity->member_id,
                            'store_id'=>$store_id,
                            'store_name'=>$store->name,
                            'goods_id'=>$goods['goods_id'],
                            'goods_name'=>$goods['goods_name'],
                            'goods_price'=>$goods['goods_price'],
                            'goods_num'=>$goods_item['num'],
                            'goods_image'=>$goods['goods_image']
                        ];
                        if($cart_model->validate() && $cart_model->save()){

                        }else
                            return ResultDataHelper::api(422, $cart_model->getFirstError());
                    }
                }
            }
        }else
            return ResultDataHelper::api(422, '商品不能为空');

    }

    /**
     * 更新购物车
     * @param $id
     * @return mixed|\yii\db\ActiveRecord
     * @throws NotFoundHttpException
     */
    public function actionUpdate($id)
    {
        $request = Yii::$app->request;
        $goods_num = $request->post('goods_num')??0;

        $model = $this->modelClass::findOne($id);
        if($model){
            $this->checkMemberStore($model['store_id']);
        }else
            return ResultDataHelper::api(422, '请求的数据不存在');

        if($goods_num){
            $model->goods_num = $goods_num;
            return $model->save();
        }else
            return ResultDataHelper::api(422, '商品数量不能为零');
    }

    /**
     * 删除购物车
     * @param $id
     * @return bool
     * @throws NotFoundHttpException
     */
    public function actionDelete($id)
    {
        $model = $this->modelClass::findOne($id);
        if($model){
            $this->checkMemberStore($model['store_id']);
        }else return ResultDataHelper::api(422, '请求的数据不存在');

        $model->goods_num = 0;
        return $model->save();
    }

    /**
     * 权限验证
     *
     * @param string $action 当前的方法
     * @param null $model 当前的模型类
     * @param array $params $_GET变量
     * @throws \yii\web\BadRequestHttpException
     */
    public function checkAccess($action, $model = null, $params = [])
    {
        // 方法名称
        if (in_array($action, ['view']))
        {
            throw new \yii\web\BadRequestHttpException('权限不足');
        }
    }
}
